import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const routes = [
    {
        path: "/",
        redirect: "/blog/list",
    },
    {
        path: "/login",
        component: () =>
            import(/* webpackChunkName: "blog" */ "../views/Login.vue"),
    },
    {
        path: "/register",
        component: () =>
            import(/* webpackChunkName: "blog" */ "../views/Register.vue"),
    },
    {
        path: "/admin",
        component: () =>
            import(/* webpackChunkName: "admin" */ "../views/admin/Index.vue"),
        children: [
            {
                path: "blog/list",
                component: () =>
                    import(
                        /* webpackChunkName: "admin" */ "../views/admin/BlogList.vue"
                    ),
            },
            {
                path: "blog/add",
                component: () =>
                    import(
                        /* webpackChunkName: "admin" */ "../views/admin/BlogAdd.vue"
                    ),
            },
            {
                path: "blog/detail/:bid",
                component: () =>
                    import(
                        /* webpackChunkName: "admin" */ "../views/admin/BlogDetail.vue"
                    ),
            },
        ],
    },
];

const router = new VueRouter({
    mode: "history",
    base: process.env.BASE_URL,
    routes,
});

const whiteList = ["/login", "/register"];

router.beforeEach((to, from, next) => {
    if (whiteList.includes(to.path) || window.sessionStorage.getItem("token")) {
        next();
    } else {
        next("/login");
    }
});

export default router;
